<?php

/**
 *
 */
namespace app\common\service;

use app\common\library\Auth;
use app\common\library\MyWeixin;
use app\common\model\Follow;
use app\common\model\Promoter;
use app\common\model\User;
use think\Db;
use think\Exception;

class UserService extends BaseService
{
	
	public function __construct()
	{
		$this->model = new User();
	}
	
	/**
	 * 小程序登录
	 * @param $code
	 * @return bool
	 */
	public  function smallappLogin($code) {
		
		try {
			
			if(!$code) {
				throw new Exception('code 不能为空');
			}
			
			$weixin = MyWeixin::getInstance();
			
			//获取openid和session_key
			$openidRes = $weixin->getOpenIdByCode($code);
			if(!$openidRes || !empty($openidRes['errcode'])) {
				throw new Exception($openidRes['errmsg'] ?? '获取用户openid出错');
			}
			
			$auth = Auth::instance();
			
			$openid = $openidRes['openid'];
			$userModel = new User();
			//查询是否已经存在用户
			$user = $userModel->getUserByOpenid($openid);
			if (!$user) {
				$username = 'wx_' . mt_rand(111111, 999999);
				$password = mt_rand(111111, 999999);
				
				$ret = $auth->register($username, $password, '', '',
					['smallapp_openid' => $openid, 'session_key' => $openidRes['session_key']]);
				if (!$ret) {
					throw new Exception($auth->getError());
				}
				$userId = $auth->id;
			} else {
				$userId = $user['id'];
			}
			$auth->direct($userId);
			
			//已经有帐号，直接登录
			$info = $auth->getUserinfo();
			return $info;
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * 绑定用户ID
	 * @param $userId
	 * @param $recommendUserId
	 * @return false|int
	 * @throws \think\exception\DbException
	 */
	public function bindRecommendUserId($userId, $recommendUserId)
	{
		$user = User::get($userId);
		if(!$user || $user['recommend_id']) {
			$this->error = '用户不存在或已绑定';
		}
		
		$model = new User();
		return $model->save(['recommend_id' => $recommendUserId], ['id' => $userId]);
	}
	
	public function updateById($id, $data)
	{
		if(!$id || !$data) {
			$this->error = '参数错误';
			return false;
		}
		
		
		return $this->model
			->allowField(true)
			->save($data, ['id' => $id]);
	}
	
	public function follow($userId, $followUserId)
	{
		$model = new Follow();
		$data = [
			'follow_user_id' => $followUserId,
			'user_id' => $userId,
		];
		
		$row = $model->where($data)->find();
		if(!$row) {
			$obj = new PromoterService();
			$fansRes = $obj->addFansNumber($followUserId);
			
			return $model->isUpdate(false)
				->save($data);
		}
		
		return true;
	}
	
	/**
	 * 获取推荐人三级代理
	 * @param $userId
	 * @return array
	 */
	public static function getOrderRebateUserId($userId) {
		$ids = [
			'direct_id' => 0,
			'indirect_id' => 0,
			'top_id' => 0
		];
		
		//推荐人不是代理，直接没有返利
		$direct	= self::getRecommendIdByUserId($userId);
		if($direct) {
			$ids['direct_id'] = $direct['user_id'];
		}
		if($direct['recommend_id']) {
			// 间接推荐人
			$indirect = self::getRecommendIdByUserId($direct['recommend_id']);
			if($indirect) {
				$ids['indirect_id'] = $indirect['user_id'];
			}
			
			if($indirect['recommend_id']) {
				$top = self::getRecommendIdByUserId($indirect['recommend_id']);
				if($top) {
					$ids['top_id'] = $top['user_id'];
				}
			}
		}

		
		return $ids;
	}
	
	protected static function getRecommendIdByUserId($userId)
	{
		$promoter= Db::name('promoter')->alias('p')
			->join('user u', 'p.user_id = u.id', 'left')
			->where(['p.user_id' => $userId, 'p.status' => StatusService::STATUS_NORMAL])
			->field('p.user_id, u.recommend_id')
			->find();
		return $promoter;
	}
}